---
import { UI } from "astrowind:config";

// TODO: This code is temporary
---

<script is:inline define:vars={{ defaultTheme: UI.theme || "system" }}>
  function applyTheme(theme) {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
    const matches = document.querySelectorAll(
      "[data-aw-toggle-color-scheme] > input",
    );

    if (matches && matches.length) {
      matches.forEach((elem) => {
        elem.checked = theme !== "dark";
      });
    }
  }

  if (
    (defaultTheme && defaultTheme.endsWith(":only")) ||
    (!localStorage.theme && defaultTheme !== "system")
  ) {
    applyTheme(defaultTheme.replace(":only", ""));
  } else if (
    localStorage.theme === "dark" ||
    (!("theme" in localStorage) &&
      window.matchMedia("(prefers-color-scheme: dark)").matches)
  ) {
    applyTheme("dark");
  } else {
    applyTheme("light");
  }
</script>
